*===================================================================================*
* Ado-file: 	csxmvarsel Version 1.0 
* Author: 		Chen Shao(陈志豪)
* Affiliation: 	Lanzhou University
* E-mail: 		chenzhh20@lzu.edu.cn
* License:      Mulan PSL v2
* Date: 		2025/2/17                                 
*===================================================================================*

capture program drop csxmvarsel
program define csxmvarsel
	version 16
	syntax varlist(min=2),cx(namelist) cnum(numlist)
	di in blue "晨韶学妹向您报告："
	local x ""
	local ctrlx_bst ""
	local y : word 1 of `varlist'
	foreach var in `varlist'{
		if "`var'" != "`y'"{
			local x `x' `var'
		}
	}
	local ctrlx "`cx'"
	local num =`cnum'
	local i=1
	while `i'<=`num' {
	    local resr_bst=0
		foreach var in `ctrlx'{
			qui reg `y' `var'
			local r2=e(r2)
			qui reg `y' `x' `var'
			local resr_`var'=e(r2)-`r2'
			while `resr_`var''> `resr_bst'{
				local resr_bst=`resr_`var''
				local bstvar `var'
			}
		}
		local x "`x' `bstvar'"
		local ctrlx_bst "`ctrlx_bst' `bstvar'"
		foreach var in `ctrlx'{
			if `var' != `bstvar'{
				local xs `xs' `var'
			}
		}
		local i=`i'+1
		local ctrlx `xs'
		local xs ""
	}
	di in white "建议选取的`num'个控制变量为`ctrlx_bst'"
	di in white "以下是回归分析："
	reg `y' `x'
	di in blue _n "您布置的任务已经完成，请您过目~♥"
end